package com.qqhf.hitfood.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qqhf.common.entity.AjaxResult;
import com.qqhf.common.entity.PageEntity;
import com.qqhf.hitfood.bean.core.BaseController;
import com.qqhf.hitfood.bean.entity.PosAddress;
import com.qqhf.hitfood.service.IPosAddressService;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@Api(tags = "P - 个人地址")
@RestController
@RequestMapping("/pos/address")
public class PosAddressController extends BaseController {
    @Autowired
    private IPosAddressService posAddressService;

    @GetMapping("/page")
    public AjaxResult page(PageEntity pageEntity, PosAddress posAddress) {
        return AjaxResult.success(posAddressService.page(pageEntity.toPage(), Wrappers.lambdaQuery(posAddress)));
    }

    @GetMapping("/list")
    public AjaxResult list(PosAddress posAddress) {
        return AjaxResult.success(posAddressService.list(Wrappers.lambdaQuery(posAddress)));
    }

    @PostMapping("/add")
    public AjaxResult add(@RequestBody PosAddress posAddress) {
        System.out.println("posAddress:" + posAddress);
        boolean save = posAddressService.save(posAddress);
        if (save) {
            Integer id = posAddress.getId();
            System.out.println("save地址之后，获取记录id为：" + id);
            return AjaxResult.success(id);
        }
        return AjaxResult.error("添加失败");
    }

    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody PosAddress posAddress) {
        return AjaxResult.success(posAddressService.updateById(posAddress));
    }

    @Operation(summary = "id删除用户地址")
    @DeleteMapping("/deleteById/{id}")
    public AjaxResult deleteById(@PathVariable Integer id) {
        try{
            if (posAddressService.getById(id) != null) {
                boolean b = posAddressService.removeById(id);
                if (b)
                    return AjaxResult.success("删除成功");
            }
            return AjaxResult.error("删除失败");
        } catch (Exception e){
            return AjaxResult.error("无法删除");
        }
    }

    @DeleteMapping("/delete/{ids}")
    public AjaxResult delete(@PathVariable Integer[] ids) {
        return AjaxResult.success(posAddressService.removeByIds(Arrays.asList(ids)));
    }

    @GetMapping(value = "/detail/{id}")
    public AjaxResult detail(@PathVariable("id") Integer id) {
        return AjaxResult.success(posAddressService.getById(id));
    }

    @Operation(summary = "id获取用户地址")
    @GetMapping(value = "/getUserAdd/{userId}")
    public AjaxResult getUserAdd(@PathVariable("userId") Integer userId) {
        return AjaxResult.success(posAddressService.list(new QueryWrapper<PosAddress>().eq("user_id", userId)));
    }
}
